import AdopterModel from "../../model/adopterModel/adopterModel.js"
import { GetConnection, GetResult } from "../../util/db.js"
import { JoinSQLInsertKeys, JoinSQLUpdateKeys } from "../../util/JoinSQL.js"

class AdopterService {
    /**
     * @param {AdopterModel} condition 
     * @returns {Promise<import("mysql2").ResultSetHeader>}
     */
    static async InsertAdopter(condition) {
        try {
            const model = new AdopterModel(condition)
            const conn = await GetConnection()
            let { keys, values } = model.GetKeys_Values()
            let sql = `insert into adopter`
            sql += JoinSQLInsertKeys(keys)
            const { rows: result } = await GetResult(sql, [[values]], conn, true)
            return result && result.affectedRows
        } catch (error) {
            return Promise.reject(error)
        }
    }
    /**
     * 获取全部
     */
    static async GetAdopter(onlyuser = false, onlyIsPassed = false, condition) {
        try {
            const conn = await GetConnection()
            let sql = `
SELECT a.*,b.userName,b.portraitSrc as userPortraitSrc,c.petName,c.portraitSrc as petPortraitSrc
FROM adopter a
LEFT JOIN usertable b on a.ownerID = b.id
LEFT JOIN pet c on a.petID = c.id
WHERE 1 = 1
            `
            if (!onlyIsPassed) {
                sql += '\tand a.isPassed = 0'
            }
            if (condition) {
                sql += `\tand b.userName like '%${condition}%' or a.demand like '%${condition}%'`
            }
            const { rows: result } = await GetResult(sql, undefined, conn)
            return result
        } catch (error) {
            return Promise.reject(error)
        }
    }

    /**
     * @param {AdopterModel} model
     * @param {Map} columns 
     * @returns {Promise<boolean>}
     */
    static async EditAdopter(model, columns) {
        try {
            const conn = await GetConnection()
            model = new AdopterModel(model)
            model.SetUpdateColumns(columns)
            let sql = "update adopter\t" + JoinSQLUpdateKeys(columns, model)
            let { rows } = await GetResult(sql, undefined, conn, true)
            return rows && rows.affectedRows
        } catch (error) {
            return Promise.reject(error)
        }
    }
}

export default AdopterService